-- 發起忘记密码申请


local httparg    = require("shared.api.httparg")
local response   = require("shared.api.response")
local config     = require("config")
local tag        = httparg.tag()
local assertion  = httparg.assertion
local httpclient = require "shared.http.client"

local cjson      = require "cjson.safe"
cjson.encode_max_depth(32)
cjson.decode_max_depth(32)


local  ARGS = {
  tag.body('json', 'required'),

  username  =  tag.json.username     ('string','required'),
  recipient =  tag.json.recipient    ('string'),
  sender    =  tag.json.sender       ('string', 'required'),
  subject   =  tag.json.subject      ('string', 'required'),
  body      =  tag.json.body         ('string', 'required'),
  charset   =  tag.json.charset      ('string', 'required'),
}


  local RESULT={}
do
  local GAAS_SHARED_REDIS      = config.GAAS_SHARED_REDIS
  local redis                  = require("shared.api.redis-adapter").new(GAAS_SHARED_REDIS)
  --nsq
  local producer               = require "resty.nsq.producer"
  local GAAS_NSQ               = config.GAAS_NSQ
  local prod                   = producer:new()
  local uuidObj                = require 'resty.jit-uuid'
  uuidObj.seed(os.time())




  local location   = config.ENV.DATAGATE_SERVICE .. "account"
  local headers    = ngx.req.get_headers()
  local query      = nil
  local method     = "PEEK"
  local bodyMap    = {}
  bodyMap.username = ARGS.username


  do
      headers['X-Forwarded-For'] = ngx.var.proxy_add_x_forwarded_for
  end

  local rmvLowKey             ="x-http-method-override"
  local rmvKey2               ="accept-encoding"
  for k,v in pairs(headers) do
      local low=string.lower(k)
      if low==rmvLowKey  or low==rmvKey2   then
          headers[k]=nil
      end
  end

  local requestData = cjson.encode(bodyMap)
  local email
  local account
  do
      local resp, err = httpclient.new()
                                  :uri(location)
                                  :headers(headers)
                                  :query(query)
                                  :body(requestData)
                                  :send(method, 2000, nil)

      if err or (not resp) then
          ngx.status = 500
          ngx.say(err)
          ngx.exit(ngx.OK)
      end

        ngx.log(ngx.ERR, resp.body)

        local util                  = require "proxy.game.common.util"
        local fill_response_header  = util.fill_response_header
        local is_match_content_type = util.is_match_content_type
        if not resp.body
                or not resp.headers
                or resp.status ~= 200
                or not is_match_content_type(resp, 'application/json')  then

            ngx.status = resp.status
            -- fill header except 'Server'
            fill_response_header(resp.headers)
            ngx.say(resp.body)
            ngx.exit(ngx.OK)
        end

        local respBody
        local get_content_decoder   = util.get_content_decoder
        local contentDecoder        = get_content_decoder(resp)
        if contentDecoder then
            respBody = contentDecoder.decode(resp.body)
        else
            -- 这儿理论上不应该出错
            ngx.status = 500
            ngx.say(err)
            ngx.exit(ngx.OK)
        end
        email=respBody.email
        account=respBody.account
    end

    local token= uuidObj()
    local key=token
    local value =string.format("%s:%s",ARGS.username,account)

    local ok, err = redis:set(key,value)
    if not ok then
        ngx.say("failed to set key: ", err)
        return
    end
    ok, err =  redis:pexpire(key, 1000*600) --ttl 600sec
    if not ok then
        ngx.say("failed to pexpire key: ", err)
        return
    end


    ok, err = prod:connect(GAAS_NSQ.host,GAAS_NSQ.port)
    if not ok then
        ngx.say("failed to connect: ", err)
        return
    end
    local nsqMsg      = {
          sender      = ARGS.sender,
          recipient   = email,
          subject     = ARGS.subject,
          charset     = "UTF-8"
    }

    nsqMsg.body=string.format(ARGS.body,token)
    local NSQ_MSG_BODY= cjson.encode(nsqMsg)
    ok, err = prod:pub(GAAS_NSQ.topic,NSQ_MSG_BODY )
    if not ok then
        ngx.say("failed to pub: ", err)
        return
    end
    ok, err = prod:close()
    if not ok then
        ngx.say("failed to close: ", err)
        return
    end

end

  response.success(RESULT)
